package com.itheima.atte.interceptor;


import com.itheima.common.threadlocal.UserHolder;
import com.itheima.common.util.JsonUtils;
import com.itheima.common.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否提交了请求头 Authorization
        try {
            //通过security上下文 获取到用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            boolean authenticated = authentication.isAuthenticated();
            if (authenticated) {
                //获取认证后的用户信息json字符串
                String userinfoJson = (String) authentication.getPrincipal();
                //转为用户信息对象
                UserInfo userInfo = JsonUtils.toBean(userinfoJson, UserInfo.class);
                //存入Threadlocal
                UserHolder.setUserInfo(userInfo);
            }
        } catch (Exception e) {
            return true;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
